<?php
include_once(_CORE_PATH. "mapper_prototype.php");
include_once(_APP_PATH. "business/blogs/blogs_entity.php");
class BlogsMapper extends mapper_prototype
{
	private $_source;
	
	public function __construct()
	{
		parent::__construct('blogs');
		
		$this->_source = MozgSource::get('default');
	}	
	
	static public function GetInstance()
	{
		return new self();		
	}

	public function GetById($id)
	{
		return $this->GetByProperty('mb.id', (int)$id);	
	}

	public function GetByUserId($userId)
	{
		return $this->GetByProperty('mb.user_id', (int)$userId);	
	}	
	
	private function GetByProperty($prop, $value)
	{
          return $this->_source->query("SELECT
												mb.id,
												mb.title,
												mb.about,
												mb.description,
												mb.user_id userId,
												u.username userName									   
						                     FROM
						                     	%%blog%% mb 
						                     		left join %%users%% u on(mb.user_id = u.user_id)
						                     WHERE
						                     	" .$prop. "=" . $value . "
						                    ")->fetchObject('BlogsEntity');			
	}
	
	public function GetNew()
	{
		return new BlogsEntity();
	} 
		
	private $_totalRows = 0;
	
	public function GetTotal()
	{
		return $this->_totalRows;		
	}
	
	public function GetBlogs($paginator = null)
	{   
        $stmt = $this->_source->query("SELECT SQL_CALC_FOUND_ROWS
												mb.id,
												mb.title,
												mb.about,
												mb.description,
												mb.user_id userId,
												u.username userName									   
						                     FROM
						                     	%%blog%% mb 
						                     		left join %%users%% u on(mb.user_id = u.user_id)              																 
							                 ORDER by id
							                 " .($paginator ? "LIMIT " .$paginator->GetSqlLimit() : ""). "
							               ");

        $this->_totalRows = $this->_source->query("SELECT FOUND_ROWS()")->fetchColumn();
        
	    $stmt->setFetchMode(PDO::FETCH_CLASS, 'BlogsEntity');
        return $stmt->fetchAll();		
	}	

	public function Save(BlogsEntity $obj)
	{
		if (!$this->Prepare($obj)) return false;
		
		if ($obj->GetId())
		{
			return $this->Update($obj);		
		}

		return $this->Insert($obj);
	}
	
	private function Insert(BlogsEntity $obj)
	{		
		$num = $this->_source->exec("insert into %%blog%%(title, about, description, user_id)
			            values(
					              " .$this->_source->quote($obj->GetTitle()). ",
					              " .$this->_source->quote($obj->GetAbout()). ",
					              " .$this->_source->quote($obj->GetDescription()). ",
					              " .$obj->GetUserIdSql(). "
			            )
			");		

		if ($num)
		{
			$obj->SetId($this->_source->lastInsertID());
			return true;
		}
			
		return false;
	}
	
	private function Update(BlogsEntity $obj)
	{
		$num = (bool)$this->_source->exec("update %%blog%%
										      set
												 title = " .$this->_source->quote($obj->GetTitle()). ", 
												 about = " .$this->_source->quote($obj->GetAbout()). ",
										      	 description = " .$this->_source->quote($obj->GetDescription()). ",
										      	 user_id = " .$obj->GetUserIdSql(). "
											  where 
										      	 id=" .$obj->GetId(). "
									     ");		
		
		if ($num)
		{
			return true;
		}

		return false;
	}	

	private function Prepare(BlogsEntity $obj)
	{
		if (strlen($obj->GetTitle()) < 1) 
		{
            return $this->SetErrorMessage('Введите название блога');
        }

        if (!is_null($obj->GetUserId()))
        {
		    $r = $this->_source->query("SELECT 
	        										id
	        									FROM %%blog%%
	        									WHERE 
	        										id != " .(int)$obj->GetId() . " and 
	        										user_id=" . $obj->GetUserIdSql())->fetchColumn();        
	
	        if ($r) 
	        {
	            return $this->SetErrorMessage('У выбранного пользователя уже есть блог');
	        }   		
        }
        
        return true;
	}

    public function Delete($id)
    {
        $num = (bool)$this->_source->exec("DELETE 
        											mb, mae, maet, mate, maec
		        								FROM %%blog%% mb
		        										left join %%article_entry%% mae on (mb.id = mae.blog_id)
		        										left join %%article_entry_tag%% maet on (mae.id = maet.entry_id)
		        										left join %%article_theme_entries%% mate on (mae.id = mate.entry_id)
		        										left join %%article_entry_comment%% maec on (mae.id = maec.entry_id)		        								
		        								WHERE 
		        									mb.id=" .(int)$id. "
		        								");
    	if ($num)
    	{	
    		return true;
    	}
    	return false;    
    }  	
}	